/*
*  Copyright 2019-2025 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.jiaoyou.follows.rest;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.jiaoyou.follows.domain.Follows;
import me.zhengjie.modules.jiaoyou.follows.service.FollowsService;
import me.zhengjie.modules.jiaoyou.follows.domain.dto.FollowsQueryCriteria;
import lombok.RequiredArgsConstructor;
import java.util.List;

import me.zhengjie.modules.jiaoyou.likes.domain.Likes;
import me.zhengjie.modules.jiaoyou.moments.domain.Moments;
import me.zhengjie.modules.jiaoyou.moments.mapper.MomentsMapper;
import me.zhengjie.modules.jiaoyou.users.domain.Users;
import me.zhengjie.modules.jiaoyou.users.mapper.UsersMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import me.zhengjie.utils.PageResult;

/**
* @author ztd
* @date 2025-11-19
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "关注管理")
@RequestMapping("/api/follows")
public class FollowsController {

    private final FollowsService followsService;
    private final UsersMapper usersMapper;

    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('follows:list')")
    public void exportFollows(HttpServletResponse response, FollowsQueryCriteria criteria) throws IOException {
        followsService.download(followsService.queryAll(criteria), response);
    }

    @GetMapping
    @ApiOperation("查询关注管理")
    @PreAuthorize("@el.check('follows:list')")
    public ResponseEntity<PageResult<Follows>> queryFollows(FollowsQueryCriteria criteria){
        Page<Object> page = new Page<>(criteria.getPage(), criteria.getSize());

        final PageResult<Follows> followsPageResult = followsService.queryAll(criteria,page);
        // 如果内容不为空就查询用户昵称
        final List<Follows> content = followsPageResult.getContent();
        if (CollectionUtil.isNotEmpty(content)) {
            List<Integer> userIdList = content.stream().map(Follows::getUserId).collect(Collectors.toList());
            List<Integer> followedUserIdList = content.stream().map(Follows::getFollowedId).collect(Collectors.toList());
            userIdList.addAll(followedUserIdList);
            final List<Users> users = usersMapper.selectBatchIds(userIdList);
            final Map<Integer, Users> usersMap = users.stream().collect(Collectors.toMap(Users::getId, e -> e));
            for (Follows follows : content) {
                final String userName = Optional.ofNullable(usersMap.get(follows.getUserId())).map(Users::getNickname).orElse(StrUtil.EMPTY);
                final String followUserName = Optional.ofNullable(usersMap.get(follows.getFollowedId())).map(Users::getNickname).orElse(StrUtil.EMPTY);
                follows.setUserName(userName);
                follows.setFollowedName(followUserName);
            }
        }
        return new ResponseEntity<>(followsPageResult, HttpStatus.OK);
    }

    @PostMapping
    @Log("新增关注管理")
    @ApiOperation("新增关注管理")
    @PreAuthorize("@el.check('follows:add')")
    public ResponseEntity<Object> createFollows(@Validated @RequestBody Follows resources){
        followsService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改关注管理")
    @ApiOperation("修改关注管理")
    @PreAuthorize("@el.check('follows:edit')")
    public ResponseEntity<Object> updateFollows(@Validated @RequestBody Follows resources){
        followsService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除关注管理")
    @ApiOperation("删除关注管理")
    @PreAuthorize("@el.check('follows:del')")
    public ResponseEntity<Object> deleteFollows(@ApiParam(value = "传ID数组[]") @RequestBody List<Integer> ids) {
        followsService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}